package org.rcy.framework.mq.serializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.rcy.framework.api.mq.AbstractMessage;

import java.io.IOException;

public class JsonSerializer<M extends AbstractMessage> implements Serializer<M> {
    private ObjectMapper mapper = new ObjectMapper();
    private static JsonSerializer jsonSerializer = new JsonSerializer(); //饿汉式单例

    private JsonSerializer() {
        this.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        this.mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        this.mapper.setVisibility(this.mapper.getSerializationConfig()
                .getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE));
    }

    public static JsonSerializer getInstance() {
        return jsonSerializer;
    }

    public byte[] serialize(M message) throws Exception {
        return this.mapper.writeValueAsBytes(message);
    }

    public M deserialize(byte[] body, Class<?> valueType) throws Exception {
        return (M)this.mapper.readValue(body, valueType);
    }

    @Override
    public void close() throws IOException {

    }
}